package store.swing.product;

import store.domain.Product;
import store.swing.DefaultFrame;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;


public class ProductInfoFrame extends DefaultFrame {
    private Product product;

    public ProductInfoFrame(Product product) {
        this.product = product;
        initComponents();
    }

    private void initComponents() {
        setTitle("Информация о товаре");

        JPanel infoPanel = new JPanel(new GridBagLayout());
        GridBagLayout layout = (GridBagLayout) infoPanel.getLayout();
        layout.columnWidths = new int[]{0, 0, 0, 0};
        layout.rowHeights = new int[]{0, 0, 0, 0};
        layout.columnWeights = new double[]{0.0, 0.0, 1.0, 1.0E-4};
        layout.rowWeights = new double[]{0.0, 0.0, 1.0, 1.0E-4};

        GridBagConstraints c = new GridBagConstraints();
        c.insets = new Insets(5, 5, 5, 5);
        c.fill = GridBagConstraints.BOTH;

        JLabel eanLabel = new JLabel("Артикул:");
        c.gridx = 1;
        c.gridy = 0;
        infoPanel.add(eanLabel, c);

        JLabel eanValueLabel = new JLabel(product.getProductEan());
        c.gridx = 2;
        c.gridy = 0;
        infoPanel.add(eanValueLabel, c);

        JLabel nameLabel = new JLabel("Название:");
        c.gridx = 1;
        c.gridy = 1;
        infoPanel.add(nameLabel, c);

        JLabel nameValueLabel = new JLabel(product.getNameRuRu());
        c.gridx = 2;
        c.gridy = 1;
        infoPanel.add(nameValueLabel, c);

        JLabel descriptionLabel = new JLabel("Описание:");
        c.gridx = 1;
        c.gridy = 2;
        c.anchor = GridBagConstraints.NORTH;
        c.fill = GridBagConstraints.HORIZONTAL;
        infoPanel.add(descriptionLabel, c);

        JLabel descriptionValueLabel = new JLabel("<html>" + product.getDescriptionRuRu() + "</html>");
        c.gridx = 2;
        c.gridy = 2;
        infoPanel.add(descriptionValueLabel, c);

        Image image = getImage();
        if (image != null) {
            JLabel imageLabel = new JLabel(new ImageIcon(image));
            c.gridx = 0;
            c.gridy = 0;
            c.gridheight = 3;
            infoPanel.add(imageLabel, c);
        }

        add(infoPanel);
    }

    private Image getImage() {
        Image image = null;
        try {
            String imagesURL = "http://freiya.com.ua/components/com_jshopping/files/img_products/";
            URL imageURL = new URL(imagesURL + product.getImage());
            image = ImageIO.read(imageURL);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;
    }
}
